<script setup>
import {defineEmits, defineProps, ref, computed,watch} from "vue";
const emit = defineEmits(['current-change'])
const props = defineProps(['pageSize','total','span'])
const pages = ref([])
const index = ref(1)
const last = ref(-1)
function clickPage(e,currentPage) {
  e.preventDefault();
  index.value = currentPage
  computedPage(props.span||3,computedLastPage.value,currentPage)
  emit('current-change',currentPage)
}

watch(props,(newProps) => {
  last.value = computedLastPage
  index.value = 1
  computedPage(newProps.span||3,computedLastPage.value,index.value)
})

function computedPage(span,max,index){
  let firstExtendStore = extendStore(index,span,true)
  let lastExtendStore = extendStore(index,span,false)
  let firstStore = normalStore(index,span,1,true)
  let lastStore = normalStore(index,span,max,false)
  let firstDifferenceValue = span - firstStore.length
  let lastDifferenceValue = span - lastStore.length
  let tmpFirstExtendStore = []
  if(lastDifferenceValue > 0){
    tmpFirstExtendStore = firstExtendStore.slice(span-lastDifferenceValue,span).filter(num=>num>=1)
  }
  let tmpLastExtendStore = []
  if(firstDifferenceValue > 0){
    tmpLastExtendStore = lastExtendStore.slice(0,firstDifferenceValue).filter(num=>num<=max)
  }
  pages.value = [...tmpFirstExtendStore,...firstStore,index,...lastStore,...tmpLastExtendStore]
}

function normalStore(index,span,limit,asc){
  let result = []
  for(let i=1;i<=span;i++){
    let a = asc?index-span+i-1:index+i
    if(asc?(a>=limit):(a<=limit))
      result.push(a)
  }
  return result
}

function extendStore(index,span,asc){
  let result = []
  for(let i=1;i<=span;i++){result.push(index+span*(asc?-1:1)+i-(asc?span+1:0))}
  return result
}

const computedLastPage = computed(()=>{
  return Math.ceil(props.total/props.pageSize)
})
</script>

<template>
  <nav class="app-pagination" v-if="pages.length">
    <ul class="pagination justify-content-center">
      <template v-for="(page,i) in pages" :key="page">
        <template v-if="i === 0">
          <li class="page-item" :class="(index === 1?' disabled':'')">
            <a class="page-link" href="#" @click="clickPage($event,1)" tabindex="-1" aria-disabled="true">首页</a>
          </li>
        </template>
        <li class="page-item" :class="(page === index)?' active':''">
          <a class="page-link" href="#" @click="clickPage($event,page)">{{page}}</a>
        </li>
        <template v-if="i === pages.length - 1">
          <li class="page-item" :class="(index === last.value?' disabled':'')">
            <a class="page-link" href="#" @click="clickPage($event,last.value)">尾页</a>
          </li>
        </template>
      </template>
    </ul>
  </nav>
</template>

<style scoped>

</style>